package core.plugins;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class UPCDatabase_com implements IProductIDPlugin 
{
	private IProductIDPlugin nextPlugin;
	private int startIndex = 37;
	
	public UPCDatabase_com()
	{
		nextPlugin = null;
	}
	
	@Override
	public String idProduct(String barcode) 
	{
		String result = upcDatabaseLookup(barcode);
		if(result != null)
			return result;
		if(nextPlugin != null)
			return nextPlugin.idProduct(barcode);
		else
			return null;
	}

	@Override
	public void setNextPlugin(IProductIDPlugin next_plugin) 
	{
		nextPlugin = next_plugin;
	}

	@Override
	public IProductIDPlugin getNextPlugin() 
	{
		return nextPlugin;
	}
	
	private String upcDatabaseLookup(String barcode)
	{
		String url = "http://www.upcdatabase.com/item/"+barcode;
		try 
		{
			URL databaseURL = new URL(url);
			BufferedReader in;
			in = new BufferedReader(
				 new InputStreamReader(databaseURL.openStream()));
			

			String inputLine;
			while ((inputLine = in.readLine()) != null)
			{
			        if(inputLine.contains("UPC Database: Item Record"))
			        {
			        	return findDescription(in);
			        }
			}
			in.close();			
			
		} 
		catch (MalformedURLException e) 
		{
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println("Plugin Error, Bad URL");
			
		}
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			//e.printStackTrace();
			System.out.println("Plugin Error, IOException");
			
		}
		catch (Exception e)
		{
			System.out.println("Plugin Error, please check internet connection");
		}
		
		return null;
	}
	
	private String findDescription(BufferedReader in) throws IOException
	{
		String inputLine;
		while ((inputLine = in.readLine()) != null)
		{
		        if(inputLine.contains("Description"))
		        {
		        	int endIndex = inputLine.lastIndexOf("</td>");
		        	String description = (String) inputLine.subSequence(startIndex, endIndex);
		        	in.close();
		        	return description;
		        }
		}
		in.close();
		return null;
	}

}
